package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Set;

import com.ruoyi.common.utils.RequestUtil;
import com.ruoyi.common.utils.googleAuth.GoogleAuthenticator;
import com.ruoyi.system.service.IBaseWhitelistIpsService;
import com.ruoyi.system.service.ISysUserService;
import org.iherus.codegen.qrcode.SimpleQrcodeGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController {
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private IBaseWhitelistIpsService iBaseWhitelistIpsService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody, HttpServletRequest request) {
        String lastIp = RequestUtil.getIpAddrByRequest(request);
        // 判断是否为黑名单数据
        Boolean isTrue = iBaseWhitelistIpsService.findByIp(lastIp);
        if (!isTrue && !loginBody.getUsername().equals("admin")) {
            return AjaxResult.error(-1, "IP存在风险，请联系客服-" + lastIp);
        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid(), loginBody.getDynamicGoogleCode());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }


    /**
     * 生成 Google 密钥，两种方式任选一种
     */
    @GetMapping("getSecretKey")
    public String getSecretKey() {
        return GoogleAuthenticator.getSecretKey();
    }

    /**
     * 生成二维码，APP直接扫描绑定，两种方式任选一种
     */
    @GetMapping("getQrcode")
    public void getQrcode(@RequestParam("name") String name, @RequestParam("userId") Long userId, HttpServletResponse response) throws Exception {
        String secretKey = GoogleAuthenticator.getSecretKey();
        iSysUserService.updateUserGoogleCode(secretKey, userId);
        // 生成二维码内容
        String qrCodeText = GoogleAuthenticator.getQrCodeText(secretKey, name, "");
        // 生成二维码输出
        new SimpleQrcodeGenerator().generate(qrCodeText).toStream(response.getOutputStream());
    }

    /**
     * 获取code
     */
    @GetMapping("getCode")
    public String getCode(@RequestParam("secretKey") String secretKey) {
        return GoogleAuthenticator.getCode(secretKey);
    }

    /**
     * 验证 code 是否正确
     */
    @GetMapping("checkCode")
    public Boolean checkCode(@RequestParam("secretKey") String secretKey, @RequestParam("code") String code) {
        return GoogleAuthenticator.checkCode(secretKey, Long.parseLong(code), System.currentTimeMillis());
    }
}
